/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.orderQuestion;

import static ru.irenproject.it.XmlUtils.find;
import static ru.irenproject.it.XmlUtils.findChild;
import static ru.irenproject.it.XmlUtils.getChild;
import static ru.irenproject.it.XmlUtils.getChildren;
import static ru.irenproject.it.XmlUtils.xmlValueToInteger;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.w3c.dom.Element;

import ru.irenproject.it.It;
import ru.irenproject.it.ItReader;
import ru.irenproject.it.QuestionReader;
import ru.irenproject.store.Store;

@Singleton public final class OrderQuestionReader implements QuestionReader {
  @Inject OrderQuestionReader() {}

  @Override public OrderQuestion read(ItReader in, Element e, Store store) {
    OrderQuestion res = store.create(OrderQuestion.class);
    in.readPad(findChild(e, It.ELEM_CONTENT), res.formulation());

    Element xmlOptions = findChild(e, It.ELEM_ORDER_OPTIONS);
    String itemLimit = find(xmlOptions, It.ATTR_SEQUENCE_ITEMS_USED);
    if (!itemLimit.equals(It.VAL_ALL)) {
      res.setItemLimit(xmlValueToInteger(itemLimit));
    }

    String distractorLimit = find(xmlOptions, It.ATTR_DISTRACTORS_USED);
    if (!distractorLimit.equals(It.VAL_ALL)) {
      res.setDistractorLimit(xmlValueToInteger(distractorLimit));
    }

    Element xmlSequence = getChild(e, It.ELEM_SEQUENCE);
    if (xmlSequence != null) {
      for (Element xmlSequenceItem : getChildren(xmlSequence, It.ELEM_SEQUENCE_ITEM)) {
        readSequenceItem(in, xmlSequenceItem, res);
      }
    }

    Element xmlDistractors = getChild(e, It.ELEM_DISTRACTORS);
    if (xmlDistractors != null) {
      for (Element xmlDistractor : getChildren(xmlDistractors, It.ELEM_DISTRACTOR)) {
        readDistractor(in, xmlDistractor, res);
      }
    }

    return res;
  }

  private void readSequenceItem(ItReader in, Element e, OrderQuestion out) {
    in.readPad(findChild(e, It.ELEM_CONTENT), out.addItem());
  }

  private void readDistractor(ItReader in, Element e, OrderQuestion out) {
    in.readPad(findChild(e, It.ELEM_CONTENT), out.addDistractor());
  }
}
